#!/usr/bin/php
<?php

const MAX = 1024;

function main($argc, & $argv)
{
    $sd = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
    if (!$sd) {
        echo socket_strerror(socket_last_error($sd)), PHP_EOL;
        return 0;
    }

    if (!socket_bind($sd, "3.3.3.9", 9999)) {
        echo socket_strerror(socket_last_error($sd)), PHP_EOL;
        return 0;
    }

    $file = "";
    $count = 0;
    while (1) {
        $len = socket_recvfrom($sd, $buf, MAX, 0, $ip, $port);
        printf("recv[%d]: %d\n", ++$count, $len);
        $file .= $buf;
        socket_sendto($sd, $len, strlen($len), 0, $ip, $port);
        if ($len < 1024)
            break;
    }

    file_put_contents('./down.file', $file);

    socket_close($sd);

    return 0;
}

exit(main($argc, $argv));

